/**
 * @api post model.
 *
 * User: yunshengzhu
 * Date: 2020/12/1
 * Time: 下午6:15
 */
package model

func MerchantTypeAll() (list []MerchantTypeDb, err error) {
	list = make([]MerchantTypeDb, 0)
	return list, db.Order("order_id asc").Find(&list).Error
}

func CreateMerchant(obj MerchantDb) error {
	return db.Create(&obj).Error
}

func GetMerchantUserId(userId int64) (obj MerchantDb, err error) {
	return obj, db.Where("user_id=?", userId).First(&obj).Error
}

func GetMerchantMid(mid int64) (obj MerchantDb, err error) {
	return obj, db.Where("mid=?", mid).First(&obj).Error
}

func UpdateMerchant(obj MerchantDb) error {
	return db.Exec("update t_merchant set status=?,excuse=?,name=?,phone=?,address=?,business_license=?,lat=?,lon=?,audit_time=?,msg=?,type_id=?,logo=?,m_name=?,`desc`=? where mid=?",
		obj.Status, obj.Excuse, obj.Name, obj.Phone, obj.Address, obj.BusinessLicense, obj.Lat, obj.Lon, obj.AuditTime,
		obj.Msg, obj.TypeId, obj.Logo, obj.MName, obj.Desc, obj.Mid).Error
}

func NearbyMerchantList(lon string, lat string, page, size, order, typeId int) (list []MerchantDistanceDb, err error) {
	list = make([]MerchantDistanceDb, 0)
	tx := db
	tx.Where("mid <>-1")
	switch order {
	case 1:
		tx = tx.Order("distance asc")
	case 2:
		tx = tx.Order("distance desc")
	case 3:
		tx = tx.Order("min_price asc")
	case 4:
		tx = tx.Order("min_price desc")
	case 5:
		tx = tx.Order("sold asc")
	case 6:
		tx = tx.Order("sold desc")
	default:

	}

	if typeId > 0 {
		tx = tx.Where("type_id=?", typeId)
	}

	err = tx.Select(`*,round((st_distance(point(lon, lat),point(?, ?)) / 0.0111) * 1000)AS distance`, lon, lat).Where("status=1").
		Offset((page - 1) * size).Limit(size).Find(&list).Error
	return list, err
}

func GetMerchantCount(status int) (int64, error) {
	count := MerchantCountDb{}
	if status >= 0 {
		return count.Count, db.Select("count(*) as count").Where("mid<>-1 and status=?", status).Take(&count).Error
	}
	return count.Count, db.Select("count(*) as count").Where("mid<>-1 ").Take(&count).Error
}

func GetMerchantTypeIdCount(status, typeId int) (int64, error) {
	count := MerchantCountDb{}
	tx := db
	tx = tx.Where("mid<>-1")
	if status >= 0 {
		tx = tx.Where("status=?", status)
	}
	if typeId > 0 {
		tx = tx.Where("type_id=?", typeId)
	}
	return count.Count, tx.Select("count(*) as count").Take(&count).Error
}

func GetMerchantList(status int, page, size int) (list []MerchantDb, err error) {
	list = make([]MerchantDb, 0)
	tx := db
	tx = tx.Where("mid<>-1")
	if status >= 0 {
		tx = tx.Where("status=?", status)
	}
	err = tx.Order("create_time asc").Offset((page - 1) * size).Limit(size).Find(&list).Error
	return list, err
}
